package com.harmontronics.hanma.paas.paas.config;


import com.harmontronics.hanma.paas.paas.interceptor.AppReportDataSourceInterceptor;
import com.harmontronics.hanma.paas.paas.interceptor.AppTokenValidInterceptor;
import com.harmontronics.mos.sdk.TokenRefreshAndValidInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * MVC配置
 *
 * @date 2017-04-20 22:30
 */
@Configuration
@ConditionalOnMissingClass("com.harmontronics.hanma.paas.paas.interceptor.TokenValidInterceptor")
public class AppWebMvcConfig implements WebMvcConfigurer {

    @Value("${local.imgfile.prefix}")
    private String prefix;

    @Value("${local.imgfile.localWinAddress}")
    private String localWinAddress;

    @Value("${local.imgfile.localLinuxAddress}")
    private String localLinuxAddress;

    @Value("${mos.oss.enabled:false}")
    private Boolean mosEnabled;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        String localAddress = "";
        if (System.getProperty("os.name").toLowerCase().contains("windows")) {
            localAddress = localWinAddress;
        } else {
            localAddress = localLinuxAddress;
        }
        registry.addResourceHandler(prefix).addResourceLocations("file:" + localAddress);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        if (mosEnabled != null && mosEnabled) {
            registry.addInterceptor(tokenRefreshAndValidInterceptor())
                    .addPathPatterns("/api/**");
        } else {
            registry.addInterceptor(appTokenValidInterceptor())
                    .addPathPatterns("/api/**");
        }
        registry.addInterceptor(appReportDataSourceInterceptor())
                .addPathPatterns("/api/hmureport/**");
    }

    @Bean
    public AppTokenValidInterceptor appTokenValidInterceptor() {

        return new AppTokenValidInterceptor();
    }

    @Bean
    public TokenRefreshAndValidInterceptor tokenRefreshAndValidInterceptor() {
        return new TokenRefreshAndValidInterceptor("hanma");
    }

    @Bean
    public AppReportDataSourceInterceptor appReportDataSourceInterceptor() {
        return new AppReportDataSourceInterceptor();
    }

}
